//package com.lw.service.impl;
//
//import com.alibaba.fastjson.JSONArray;
//import com.alibaba.fastjson.JSONObject;
//import com.lw.common.utils.GlobalConstants;
//import com.lw.common.vo.Leave;
//import com.lw.common.vo.Receipt;
//import com.lw.service.IActivitiService;
//import jakarta.annotation.Resource;
//import org.apache.logging.log4j.LogManager;
//import org.apache.logging.log4j.Logger;
//import org.flowable.bpmn.model.BpmnModel;
//import org.flowable.common.engine.impl.identity.Authentication;
//import org.flowable.engine.*;
//import org.flowable.engine.history.HistoricActivityInstance;
//import org.flowable.engine.history.HistoricProcessInstance;
//import org.flowable.engine.repository.Deployment;
//import org.flowable.engine.runtime.ProcessInstance;
//import org.flowable.engine.task.Comment;
//import org.flowable.image.ProcessDiagramGenerator;
//import org.flowable.image.impl.DefaultProcessDiagramGenerator;
//import org.flowable.task.api.Task;
//import org.springframework.stereotype.Service;
//import org.springframework.util.StringUtils;
//
//import java.io.InputStream;
//import java.util.ArrayList;
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
//
//@Service
//public class ActivitiServiceImpl implements IActivitiService {
//
//    @Resource
//    TaskService taskService;
//
//    @Resource
//    RepositoryService repositoryService;
//
//    @Resource
//    RuntimeService runtimeService;
//
//    @Resource
//    HistoryService historyService;
//
//    @Resource
//    ProcessEngine processEngine;
//
//    private final Logger logger = LogManager.getLogger(ActivitiServiceImpl.class);
//
//    public List<Deployment> getProcessDeployList(Integer page, Integer limit) {
//        return repositoryService.createDeploymentQuery().listPage(page, limit);
//    }
//
//    public Long getProcessDeployCount() {
//        return repositoryService.createDeploymentQuery().count();
//    }
//
//    /**
//     * includeProcessVariables(); 查询个人流程任务时候，指定流程变量，
//     * 否则（集合）无法查询流程变量，很重要 我找了很久才找到的办法 。。
//     */
//    public List<HistoricProcessInstance> getMyWorkFlows(Integer page, Integer limit, String loginId) {
//        return historyService.createHistoricProcessInstanceQuery().startedBy(loginId).orderByProcessInstanceStartTime().desc().listPage(page, limit);
//    }
//
//    public Long getMyWorkFlowsCount(String loginId) {
//        return historyService.createHistoricProcessInstanceQuery().startedBy(loginId).count();
//    }
//
//    @Override
//    public InputStream getProcessDiagram(String processInstanceId) {
//        //获得流程实例
//        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
//                .processInstanceId(processInstanceId).singleResult();
//        String processDefinitionId = "";
//        if (processInstance == null) {
//            //查询已经结束的流程实例
//            HistoricProcessInstance processInstanceHistory =
//                    historyService.createHistoricProcessInstanceQuery()
//                            .processInstanceId(processInstanceId).singleResult();
//            if (processInstanceHistory == null)
//                return null;
//            else
//                processDefinitionId = processInstanceHistory.getProcessDefinitionId();
//        } else {
//            processDefinitionId = processInstance.getProcessDefinitionId();
//        }
//        //获取BPMN模型对象
//        BpmnModel model = repositoryService.getBpmnModel(processDefinitionId);
//        //获取流程实例当前的节点，需要高亮显示
//        List<String> currentActs = new ArrayList<>();
//        if (processInstance != null)
//            currentActs = runtimeService.getActiveActivityIds(processInstance.getId());
//        ProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
////        InputStream inputStream = generator.generateDiagram(model, "png", currentActs, currentActs, "宋体", "微软雅黑", "黑体", null, 1.0D);
//        InputStream inputStream =generator.generateDiagram(model, "png", currentActs, currentActs, "宋体", "微软雅黑", null, null,1.0D, false);
//        return inputStream;
//    }
//
//
//    /**
//     * 启动流程
//     * 提示: startProcessInstanceByKey和startProcessInstanceById 启动区别你可知道?
//     * 优点: key方式启动,当流程重新部署时,默认最新流程
//     * id方式启动流程,不会更改. id必须更新才行, 而key不需要变动.
//     * by lw on 2020年11月8日 12:21:27
//     */
//    @Override
//    public Map<String, String> startProcessInstanceByKey(String globalMyFirstWorkflow, String loginId) {
//        //1.设置activiti7流程发起者, 这高版本与5和6有所区别
//        Authentication.setAuthenticatedUserId(loginId);
//
//        //2.启动流程
//        Map<String, String> variable = new HashMap<>();
//        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(GlobalConstants.GLOBAL_MY_FIRST_WORKFLOW);
//        variable.put("processInstanceId", processInstance.getProcessInstanceId());
//        variable.put("processDefinitionId", processInstance.getProcessDefinitionId());
//        return variable;
//    }
//
//    @Override
//    public void complete(String processInstanceId, Map<String, Object> variable, Leave leave) {
//        Task task = taskService.createTaskQuery().processInstanceId(processInstanceId).singleResult();
//        if (task == null) {
//            throw new RuntimeException("无法查到实例ID:" + processInstanceId + " 的流程实力");
//        }
//        taskService.complete(task.getId(), variable);
//        runtimeService.setProcessInstanceName(processInstanceId, leave.getLeaveUser() + "的请假流程");
//    }
//
//    @Override
//    public Map<String, Object> getMyApplyDetails(String processInstanceId) {
//        Map<String, Object> result = new HashMap<>();
//        //1.批注查询
//        List<HistoricActivityInstance> historicActivityInstanceList = historyService.createHistoricActivityInstanceQuery().processInstanceId(processInstanceId).orderByHistoricActivityInstanceStartTime().asc().list();
//        JSONArray  activityJsonArray = new JSONArray();
//        for (HistoricActivityInstance historicActivityInstance : historicActivityInstanceList) {
//            JSONObject jsonObject = new JSONObject();
//            List<Comment> comment = taskService.getTaskComments(historicActivityInstance.getTaskId());
//            if (comment.size() > 0) {
//                jsonObject.put("comment", comment.get(0));
//            }
//            jsonObject.put("historicActivityInstance", historicActivityInstance);
//            activityJsonArray.add(jsonObject);
//        }
//        result.put("commentList", activityJsonArray);
//        //2.申请详情信息查询;
//        HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).includeProcessVariables().singleResult();
//        Map<String, Object> processVariables = historicProcessInstance.getProcessVariables();
//        Object leave = processVariables.get("leave");
//        Map<String, Object> leaveMap = null; //CommonUtil.bean2Map(leave); //将Object对象转为Map结构
//        result.putAll(leaveMap);
//        result.put("taskName", historicProcessInstance.getName());
//        result.put("createTime", historicProcessInstance.getStartTime());
//        result.put("processInstanceId", processInstanceId);
//
//
////        Task task = taskService.createTaskQuery().processInstanceId(processInstanceId).includeProcessVariables().singleResult();
////        Map<String, Object> processVariables = task.getProcessVariables();
////        Object leave = processVariables.get("leave");
////        Map<String, Object> leaveMap = CommonUtil.bean2Map(leave); //将Object对象转为Map结构
////        result.putAll(leaveMap);
////        result.put("taskName", task.getName());
////        result.put("createTime", task.getCreateTime());
////        result.put("processInstanceId", task.getProcessInstanceId());
//        return result;
//    }
//
//    @Override
//    public List<org.flowable.task.api.Task> getMyTaskWorkFlowsPage(Integer pageNum, Integer pageSize, String loginName) {
//        List<org.flowable.task.api.Task> tasks = taskService.createTaskQuery().taskCandidateOrAssigned(loginName).includeProcessVariables().listPage(pageNum, pageSize);
//        return tasks;
//    }
//
//    @Override
//    public Long getMyTaskWorkFlowsPageCount(String loginName) {
//        return taskService.createTaskQuery().taskCandidateOrAssigned(loginName).count();
//    }
//
//    @Override
//    public void verifyMyTask(Receipt receipt, Map<String, Object> variable) {
//        if (StringUtils.isEmpty(receipt.getUserId())) {
//            throw new RuntimeException("userId 不能为空");
//        }
//        Authentication.setAuthenticatedUserId(receipt.getUserId());
//        taskService.addComment(receipt.getTaskId(), null, receipt.getNote());
//        taskService.complete(receipt.getTaskId(), variable);
//    }
//
//}
